package com.platform.mobile.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.platform.bean.PageInfo;
import com.platform.mobile.bean.AddCourseRequest;
import com.platform.mobile.bean.AddFollowedRequest;
import com.platform.mobile.bean.AddHospitalRecordRequest;
import com.platform.mobile.bean.AddPaitentRequest;
import com.platform.mobile.bean.AssistantInfo;
import com.platform.mobile.bean.ContactInfo;
import com.platform.mobile.bean.CourseBean;
import com.platform.mobile.bean.CourseResBean;
import com.platform.mobile.bean.FollowedBean;
import com.platform.mobile.bean.FollowedListBean;
import com.platform.mobile.bean.GetCourseRequest;
import com.platform.mobile.bean.GetCourseResponse;
import com.platform.mobile.bean.GetFollowedByRecrodRequest;
import com.platform.mobile.bean.GetFollowedByRecrodResponse;
import com.platform.mobile.bean.GetFollowedRequest;
import com.platform.mobile.bean.GetFollowedResponse;
import com.platform.mobile.bean.GetHospitalRecordRequest;
import com.platform.mobile.bean.GetHospitalRecordResponse;
import com.platform.mobile.bean.GetTransferRequest;
import com.platform.mobile.bean.GetTransferResponse;
import com.platform.mobile.bean.GroupsBean;
import com.platform.mobile.bean.HospitalRecordBean;
import com.platform.mobile.bean.LoginAssistant;
import com.platform.mobile.bean.LoginDoctor;
import com.platform.mobile.bean.Paitent;
import com.platform.mobile.bean.PaitentListBean;
import com.platform.mobile.bean.SearchFollowedRequest;
import com.platform.mobile.bean.SearchPaitentRequest;
import com.platform.mobile.bean.TransferBean;
import com.platform.mobile.dao.PaitentDao;
import com.platform.mobile.entity.VisitCourseDisease;
import com.platform.mobile.entity.VisitCourseRes;
import com.platform.mobile.entity.VisitFollowed;
import com.platform.mobile.entity.VisitGroups;
import com.platform.mobile.entity.VisitHospitalRecord;
import com.platform.mobile.entity.VisitUser;
import com.platform.mobile.service.PaitentService;
import com.platform.mobile.session.SessionManager;
import com.platform.tool.HelpFunctions;

@Service
public class PaitentServiceImpl implements PaitentService{

	@Autowired
	private PaitentDao dao;
	
	@Override
	public PaitentListBean getPaitents(PageInfo pageInfo) {
		
		List<VisitUser> list = dao.getUsersList(pageInfo);
		PaitentListBean beanList = new PaitentListBean();
		
		if(!HelpFunctions.isEmpty(list)){
			entityToBean(beanList,list,
					dao.getTotalCountOfUsers(),
					pageInfo.getCurrPage());
		}
		
		return beanList;
	}
	
	@Override
	public PaitentListBean searchPaitents(SearchPaitentRequest request) {
		
		PaitentListBean bean = new PaitentListBean();
		
		List<VisitUser> listByName 
			= dao.getUsersLikeName(request);
		
		List<VisitUser> listByPhone
			= dao.getUsersLikePhone(request);
		
		int nameCount = dao.getUsersLikeNameCount(request);
		int phoneCount = dao.getUsersLikePhoneCount(request);
		
		int totalCount = nameCount + phoneCount;
		
		if(!HelpFunctions.isEmpty(listByName)){
			entityToBean(bean,listByName,
					totalCount,0);
		}
		
		if(!HelpFunctions.isEmpty(listByPhone)){
			entityToBean(bean,listByPhone,
					totalCount,0);
		}
		
		return bean;
	}
	
	private void entityToBean(PaitentListBean beanList,
			List<VisitUser> entityList
			,int totalCount,int currentPage){
		
		beanList.setTotalCount(totalCount);
		//beanList.setPageTotal(pageTotal);
		beanList.setCurrentPage(currentPage);
		
		for(VisitUser entity : entityList){
			Paitent paitent = new Paitent();
			paitent.setName(entity.getReal_name());
			paitent.setSex(entity.getSex());
			paitent.setPhone(entity.getPhone());
			paitent.setBirthday(entity.getBirthday());
			paitent.setMarriage(entity.getMarriage());
			paitent.setAddress(entity.getAddress());
			paitent.setId(entity.getId());
			
			beanList.getPaitents().add(paitent);
		}
		
	}

	@Override
	@Transactional
	public Boolean addPaitent(AddPaitentRequest request) {
		

		if(request == null) return false;
		VisitUser user = new VisitUser();
		
			user.setReal_name(request.getName());
			user.setSex(request.getSex());
			user.setPhone(request.getPhone());
			
			SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd");
			String str_birthday = formater.format(request.getBirthday());
			
			user.setBirthday(str_birthday);
			user.setMarriage(request.getMarriage());
			user.setAddress(request.getAddress());
			
			/** 默认字段赋值（NOT NULL）*/
			user.setStatus("1");
			// 默认患者
			user.setUser_type("2");
			
			user.setCert_status("0");
			dao.insertUser(user);
		
		return true;
	}

	@Override
	public GetHospitalRecordResponse searchHospitalRecord(GetHospitalRecordRequest request) {
		
		List<VisitHospitalRecord> entityList 
			= dao.getHospitalRecordById(request);
		
		GetHospitalRecordResponse response 
			= new GetHospitalRecordResponse();
		
		int totalCount = dao.getTotalCountOfHospitalRecord();
		response.setTotalCount(totalCount);
		
		if(!HelpFunctions.isEmpty(entityList)){
			for(VisitHospitalRecord record : entityList){
				HospitalRecordBean bean = new HospitalRecordBean();
				
				String userName = dao.getPatientNameById(record.getU_id());
				bean.setId(record.getID());
				bean.setName(userName);
				bean.setUserId(record.getU_id().toString()); 
				bean.setDept(record.getDept());
				bean.setInhiscode(record.getInhiscode());
				bean.setMajor(record.getMajor());
				bean.setNote(record.getNote());
				bean.setAdmissionDate(record.getADMISSION_DATE());
				bean.setDischargeDate(record.getDISCHARGE_DATE());
				bean.setOrigin(""); //TODO 有问题
				
				response.getRecordList().add(bean);
			}
		}
		return response;
	}

	@Override
	@Transactional
	public Boolean addHospitalRecord(AddHospitalRecordRequest request) {
		
		VisitHospitalRecord entity = new VisitHospitalRecord();
		entity.setU_id(request.getPatient_id());
		entity.setDept(request.getDept_name());
		entity.setDept_id(request.getDept_id());
		entity.setMajor(request.getMajor_name());
		entity.setMajor_id(request.getMajor_id());
		entity.setAssistant(request.getAid_name());
		entity.setAid_id(request.getAid_id());
		entity.setNote(request.getNote());
		
		SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		entity.setADMISSION_DATE(formater.format(request.getAdmission_date()));
		if(request.getDischarge_date() != null)
			entity.setDISCHARGE_DATE(formater.format(request.getDischarge_date()));
		
		entity.setInhiscode(request.getInhiscode());
		
		//TODO 病人来源数据库暂不支持，暂时不做处理
		//entity.setOrigin
		
		dao.insertHospitalRecord(entity);
		
		return true;
	}

	@Override
	@Transactional
	public Boolean addCourse(AddCourseRequest request) {
		
		VisitCourseDisease course = new VisitCourseDisease();
		List<VisitCourseRes> resList = new ArrayList<VisitCourseRes>();
		
		String uid = UUID.randomUUID().toString().replace("-", "");
		
		course.setID(uid);
		course.setC_name(request.getName());
		course.setC_note(request.getContent());
		course.setD_time(request.getDate());
		course.setN_record_id(request.getRecord_id());
		
		for(CourseResBean resBean : request.getPicture()){
			
			VisitCourseRes res = new VisitCourseRes();
			res.setC_picture(resBean.getPicture());
			res.setN_course_id(uid);
			
			resList.add(res);
		}
		
		dao.insertCourseDisease(course);
		for(VisitCourseRes res : resList){
			dao.insertCourseRes(res);
		}
		
		return true;
	}

	@Override
	public GetCourseResponse getCourseList(GetCourseRequest request) {
		
		GetCourseResponse response = new GetCourseResponse();
		List<VisitCourseDisease> courseList 
			= dao.getCourseList(request.getRecord_id());
		
		for(VisitCourseDisease course : courseList){
			
			CourseBean bean = new CourseBean();
			bean.setContent(course.getC_note());
			
			SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd");
			Date date = course.getD_time();
			
			bean.setDate(formater.format(date));
			
			List<VisitCourseRes> courseResList 
				= dao.getCourseResList(course.getID());
			for(VisitCourseRes courseRes : courseResList){
				CourseResBean resBean = new CourseResBean();
				resBean.setPicture(courseRes.getC_picture());
				
				bean.getPictures().add(resBean);
			}
			
			response.getCourse().add(bean);
		}
		return response;
	}

	@Override
	public GetFollowedResponse getFollowedView(GetFollowedRequest request,
			Integer aidId) {
		
		GetFollowedResponse response = new GetFollowedResponse();
		int totalCount = 0;
		Boolean isFollowed = false;
		if(request.getIsFollowed() == 1) isFollowed = true;
		
		totalCount = dao.getTotalCountOfFollowedView(isFollowed
				,null,null,null);
		response.setPageTotal(totalCount);
		
		List<FollowedListBean> followedListBean 
			= dao.getFollowedView(aidId, isFollowed,null,null,null,
					request.getPageInfo());
		response.setFollowed(followedListBean);
		
		return response;
	}

	@Override
	public GetFollowedResponse searchFollowedView(SearchFollowedRequest request,
			Integer aidId) {
		
		GetFollowedResponse response = new GetFollowedResponse();
		
		List<FollowedListBean> followed = dao.getFollowedView(aidId, false, 
				request.getContent(), 
				request.getDisease(), 
				request.getTimes(), 
				request.getPageInfo());
		
		int totalCount = dao.getTotalCountOfFollowedView(false
				, request.getContent(), request.getDisease(), request.getTimes());
		
		response.setFollowed(followed);
		response.setPageTotal(totalCount);
		
		return response;
	}

	@Override
	public GetFollowedByRecrodResponse getFollowedView(GetFollowedByRecrodRequest request
			,Integer aidId) {
		
		GetFollowedByRecrodResponse response 
			= new GetFollowedByRecrodResponse();
		List<VisitFollowed> entityList
			= dao.getFollowedListByRecrodId(request.getRecord_id());
		
		for(VisitFollowed entity : entityList){
			FollowedBean bean = new FollowedBean();
			bean.setContent(entity.getFOLLOWED_CONTENT());
			bean.setDate(entity.getFOLLOWED_DATE());
			
			response.getFollowed().add(bean);
		}
		
		return response;
	}

	@Override
	@Transactional
	public Boolean AddFollowed(AddFollowedRequest request, Integer aidId) {
		
		VisitFollowed followed = new VisitFollowed();
		
		String content = request.getContent() 
				+ "  回访结果：" + request.getResult()
				+ "  满意度：" + request.getDegree();
		
		followed.setFOLLOWED_CONTENT(content);
		followed.setFOLLOWED_DATE(request.getDate());
		followed.setHOSPITAL_RECORD_ID(request.getRecord_id());
		followed.setFOLLOWED_USER_ID(aidId);
		
		short num = 1;
		followed.setSTATUS(num);
		
		dao.insertFollowed(followed);
		return true;
	}

	@Override
	public GetTransferResponse getTransferView(GetTransferRequest request
			,Integer deptId) {
		
		GetTransferResponse response = new GetTransferResponse();
		
		Boolean isTransfer = false;
		if(request.getIsTransfer() == 2) isTransfer = true;  
		
		int totalCount 
			= dao.getTotalCountOfTransferView(deptId, isTransfer, null);
		
		List<TransferBean> transferList
			= dao.getTransferView(deptId, isTransfer, null, request.getPageInfo());
		
		response.setPageTotal(totalCount);
		response.setTransfer(transferList);
		
		return response;
	}

	@Override
	public AssistantInfo getAssistantMap(Integer userId) {
		
		AssistantInfo infoBean = new AssistantInfo();
		
		List<LoginDoctor> doctor_list 
			= dao.getLoginDoctor(userId);
		
		if(!HelpFunctions.isEmpty(doctor_list)){
			for(LoginDoctor doctor : doctor_list){
				Integer ID = doctor.getID();
				LoginAssistant assistant
					= dao.getLoginAssistant(ID);
				if(assistant != null)
					doctor.setAssistant(assistant);
				
				infoBean.getDoctor_list().add(doctor);
			}
		}
		
		return infoBean;
	}

	@Override
	public List<GroupsBean> getGroups(Integer userId) {
		
		List<GroupsBean> beanList = new ArrayList<GroupsBean>();
		List<VisitGroups> groupsList = new ArrayList<VisitGroups>();
		
		groupsList = dao.getGroupsByType(userId);
		
		for(VisitGroups group : groupsList){
			
			List<ContactInfo> contact 
				= dao.getUsersByGroupIdAndUId(group.getID(), userId);
			
			GroupsBean bean = new GroupsBean();
			bean.setGroup(group);
			bean.setUsers(contact);
			
			beanList.add(bean);
		}
		
		return beanList;
	}


}
